package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Resource
    DishMapper dishMapper;

    @Resource
    SetmealMapper setmealMapper;

    @Resource
    SetmealDishMapper setmealDishMapper;

    @Resource
    DishFlavorMapper dishFlavorMapper;

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        /**
         * 将客户端根据categoryId查询得到的菜品信息放到redis后,为保证数据库和redis缓存的一致性,还需要修改这些代码:
         *      TODO 当管理端 增/删/改 餐品信息时,需要清除对应菜品在redis中的缓存
         */
        //构造redis中的key
        String key = "dish_" + dish.getCategoryId();

        //先从redis里查找
        log.info("[redis查询] 开始查询");
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);    //没有对 List 里的所有对象逐一进行类型转换 (type casting) 。如果我们只是直接转换 List 的类型的话，就会产生类型不安全的潜在风险
        if (list != null && list.size() > 0) {
            log.info("[redis查询] 查询成功");
            return list;
        }

        log.info("[redis查询] 未查询到相关数据");
        //如果redis中没有,再从数据库中查找
        List<Dish> dishList = dishMapper.selectByCategoryId(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        //将从数据库查得的数据放到redis中
        redisTemplate.opsForValue().set(key, dishVOList);


        return dishVOList;
    }

    @Override
    public PageResult findAll(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        List<DishVO> dishList = dishMapper.selectAll(dishPageQueryDTO);
        Page<DishVO> page = (Page<DishVO>) dishList;
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional          //涉及到两张表中的数据,需要开启事务
    public Integer add(DishDTO dishDTO) {
        //获得dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.ENABLE);

        //将dish添加到dish表中
        Integer tag1 = dishMapper.insert(dish);

        //新增主键返回
        Long dishId = dish.getId();

        //获得dishFlavor
        List<DishFlavor> flavors = dishDTO.getFlavors();

        //将dishFlavor添加到dish_flavor表中
        flavors.forEach(flavor -> {
            //[新增主键返回]获得新增dish在dish表中的id,并将其设置为dishFlavor中的dish_id属性
            flavor.setDishId(dishId);
//            dishFlavorMapper.insert(flavor);    //利用动态sql中的<foreach>,可改进
        });

        //上述代码的改进版: 利用动态sql中的<foreach>
        dishFlavorMapper.insertInBatches(flavors);

        //返回该方法影响到数据库dish表中记录的条数
        return tag1;
    }

    @Override
    @Transactional
    public Integer setStatus(Long id, Integer status) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();

        //如果要停售菜品,则需要停售包含该菜品的所有套餐
        if (status.equals(StatusConstant.DISABLE)) {
            //获得包含停售菜品的套餐id
            List<Long> setmealIds = setmealDishMapper.selectSetmealIdsContainingClosedDish(id);
            //停售这些套餐
            setmealIds.forEach(setmealId -> {
                Setmeal setmeal = Setmeal.builder()
                        .id(setmealId)
                        .status(StatusConstant.DISABLE)
                        .build();
                setmealMapper.update(setmeal);
            });
        }
        return dishMapper.update(dish);
    }

    @Override
    public DishVO findById(Long id) {
        Dish dish = dishMapper.selectById(id);
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    @Override
    @Transactional          //涉及到两张表中的数据,需要开启事务
    public Integer modify(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        Integer tag = dishMapper.update(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        /*flavors.forEach(flavor ->{
            dishFlavorMapper.update(flavor);    //利用动态sql中的<foreach>,可改进
        });*/

        //上述代码的改进版: 利用动态sql中的<foreach>
        dishFlavorMapper.updateInBatches(flavors);

        return tag;
    }

    @Override
    @Transactional          //涉及到两张表中的数据,需要开启事务
    public Integer remove(Integer[] ids) {
        //删除dish表中数据
        Integer tag = dishMapper.delete(ids);

        //删除dish_flavor表中数据
        dishFlavorMapper.deleteByDishId(ids);

        return tag;
    }

    @Override
    public List<Dish> findByCategoryId(Long categoryId) {
        return dishMapper.selectByCategoryId(categoryId);
    }
}